import { showToast, type ToastOptions } from "vant";
import { useCachedViewStoreHook } from "@/store/modules/cached-view";
import router from "@/router";
import type { RouteParams } from "vue-router";

/**
 * 复制文本到剪贴板
 * @param text - 要复制的文本
 * @param options - 配置选项
 */
export const copyToClipboard = async (
  text: string,
  options?: {
    successMessage?: string;
    successOptions?: ToastOptions;
    failMessage?: string;
    failOptions?: ToastOptions;
  }
): Promise<boolean> => {
  const {
    successMessage = "复制成功",
    successOptions = {
      className: "copy-success-toast"
    },
    failMessage = "复制失败，请手动复制",
    failOptions = {
      className: "copy-fail-toast"
    }
  } = options || {};

  try {
    // 现代浏览器 Clipboard API
    if (navigator.clipboard) {
      await navigator.clipboard.writeText(text);
    } else {
      // 兼容旧版浏览器的实现
      const textArea = document.createElement("textarea");
      textArea.value = text;
      textArea.style.position = "fixed";
      textArea.style.opacity = "0";
      document.body.appendChild(textArea);
      textArea.select();

      const success = document.execCommand("copy");
      document.body.removeChild(textArea);

      if (!success) {
        throw new Error("复制失败");
      }
    }

    // 显示成功提示
    showToast({
      message: successMessage,
      ...successOptions
    });

    return true;
  } catch (error) {
    console.error("复制失败:", error);

    // 显示失败提示
    showToast({
      message: failMessage,
      ...failOptions
    });

    return false;
  }
};
/**
 * 加密手机号，将中间四位替换为 *
 * @param phone - 原始手机号
 * @returns 加密后的手机号
 */
export const encryPhoneNumber = (phone: string): string => {
  if (!phone || phone.length < 11) return phone;
  return phone.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
};

/**
 * 分割金额为整数部分和小数部分
 * @param money - 金额值
 * @returns 包含整数部分和可选的小数部分的对象
 */
// 金额分割
export const payMoneySplit = (
  money: number
): {
  integerPart: string;
  decimalPart?: string;
} => {
  // 判断是否为浮点数
  if (Number.isInteger(money)) {
    // 不是浮点数，返回整数部分
    return { integerPart: money.toString() };
  } else {
    // 是浮点数，分割整数和小数部分
    const parts = money.toString().split(".");
    return {
      integerPart: parts[0],
      decimalPart: parts[1]
    };
  }
};

/**
 * 导航到指定路由并清除目标页面缓存
 * @param routeName - 目标路由名称
 * @param params - 路由参数
 * @param clearCache - 是否清除目标页面缓存，默认为true
 */
export const navigateTo = async (
  routeName: string,
  params?: RouteParams,
  clearCache: boolean = false
): Promise<void> => {
  // 清除目标页面缓存
  if (clearCache) {
    const cachedViewStore = useCachedViewStoreHook();
    cachedViewStore.delCachedView({ name: routeName } as any);
  }

  // 导航到目标路由
  await router.push({
    name: routeName,
    params: params || {}
  });
};
/**
 * 将数据存储到 localStorage
 * @param key 存储的键名
 * @param value 存储的值（任意类型）
 */
export const setLocalStorage = <T>(key: string, value: T): void => {
  try {
    const stringValue = JSON.stringify(value);
    localStorage.setItem(key, stringValue);
  } catch (error) {
    console.error(`[setLocalStorage] 存储失败 (key: ${key}):`, error);
  }
};

/**
 * 从 localStorage 获取数据
 * @param key 要获取的键名
 * @param defaultValue 获取失败时的默认值（可选）
 * @returns 解析后的数据或默认值
 */
export const getLocalStorage = <T>(key: string, defaultValue?: T): T | null => {
  try {
    const data = localStorage.getItem(key);
    if (data === null) return defaultValue || null;
    return JSON.parse(data) as T;
  } catch (error) {
    console.error(`[getLocalStorage] 解析失败 (key: ${key}):`, error);
    return defaultValue || null;
  }
};

/**
 * 从 localStorage 删除数据
 * @param key 要删除的键名
 */
export const removeLocalStorage = (key: string): void => {
  try {
    localStorage.removeItem(key);
  } catch (error) {
    console.error(`[removeLocalStorage] 删除失败 (key: ${key}):`, error);
  }
};
